package org.phoenixframework.api.sys.config.aspect;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.phoenixframework.api.sys.service.ISysLogService;
import org.phoenixframework.common.entity.SysLog;
import org.phoenixframework.common.entity.annotation.OperationLog;
import org.phoenixframework.common.tools.MyStringUtils;
import org.phoenixframework.common.tools.ServletUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2021/7/6 17:27
 * Description:
 */
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class LogAspect {

    private final ISysLogService sysLogService;

    @Pointcut("@annotation(org.phoenixframework.common.entity.annotation.OperationLog)")
    public void pointCut() {

    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "pointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "pointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    private void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        OperationLog operationLog = getOperationLog(joinPoint);
        if (operationLog == null) {
            return;
        }
        SysLog sysLog = new SysLog();
        if (StringUtils.isBlank(operationLog.title())) {
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            if (method.isAnnotationPresent(ApiOperation.class)) {
                ApiOperation log = method.getAnnotation(ApiOperation.class);
                sysLog.setTitle(log.value());
            }
        } else {
            sysLog.setTitle(operationLog.title());
        }
        sysLog.setBusinessType(operationLog.businessType().name());
        // 设置方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        sysLog.setMethodName(className + "." + methodName + "()");
        // 设置请求方式
        sysLog.setRequestMethod(ServletUtils.getRequest().getMethod());
        // 请求URL
        sysLog.setUrl(ServletUtils.getRequest().getRequestURI());
        // Ip地址
        sysLog.setIp(ServletUtils.getIp());
        // 请求参数
        if (operationLog.saveRequestParams()) {
            sysLog.setRequestParams(getRequestParams());
        }
        // 结果
        if (jsonResult == null) {
            jsonResult = "";
        }
        sysLog.setResult(MyStringUtils.substring(JSONObject.toJSONString(jsonResult), 0, 4000));
        // 错误信息
        if (e != null) {
            sysLog.setErrorMsg(MyStringUtils.substring(JSONObject.toJSONString(e.getMessage()), 0, 4000));
        }
        if (operationLog.elkEnable()) {
            log.info(JSONObject.toJSONString(sysLog));
        }
        if (operationLog.saveDataSource()) {
            sysLogService.save(sysLog);
        }

    }

    private OperationLog getOperationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(OperationLog.class);
        }
        return null;
    }

    /**
     * 获取请求的参数，放到log中
     */
    private String getRequestParams() {
        Map<String, String[]> parameterMap = ServletUtils.getRequest().getParameterMap();
        if (MyStringUtils.isNotEmpty(parameterMap)) {
            String requestParams = JSONObject.toJSONString(parameterMap);
            return MyStringUtils.substring(requestParams, 0, 4000);
        }
        return null;
    }

}
